﻿using BSF.SystemConfig;
using HuntingFishGame.H5.Models.WeChatCommon;
using HuntingFishGame.ManageDomain.BLL.GoldShopOrder;
using HuntingFishGame.ManageDomain.Model.GoldShopOrder;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace HuntingFishGame.H5.Controllers
{
    public class WeChatController : Controller
    {
        public ActionResult OrderPayRequest(string orderId, string openid, string toUrl)
        {
            //JSAPI支付预处理
            try
            {
                BSF.Log.CommLog.Write("测试：" + openid);
                //openid = "oSWW1wpm5HDrfECX2WBemyiEU7mY";
                ViewBag.wxJsApiParam = "";
                toUrl = string.IsNullOrEmpty(toUrl) == true ? Url.Action("PaymentSuccess", "GoldShopOrder", new { area = string.Empty }) : toUrl;//支付后跳转地址               
                ViewBag.ToUrl = toUrl;
                bool status = GoldShopOrderBLL.GetPayStatus(BSFConfig.MainConnectString, orderId);
                GoldShopOrderModel orderModel = GoldShopOrderBLL.GetInfo(BSFConfig.MainConnectString, orderId.ToString());
                if (!status)
                {
                    ViewBag.CancelUrl = Url.Action("Home", "Index", new { area = string.Empty, openid = openid });
                    string goodsnamestr = orderModel.text;
                    string tradeCode = orderId.ToString();//Dyd.Pay.WxPay.WxPayApi.GenerateOutTradeNo();//支付请求订单号
                    string description = "猎鱼岛购买金币";
                    //spmcstr = spmcstr.Length > 90 ? spmcstr.Substring(0, 90) + "..." : spmcstr;//商品名称字符控制
                    string paramStr = ""; //(附加参数，原样返回)
                    //paramStr = paramStr.Length > 60 ? paramStr.Substring(0, 60) : paramStr;//微信参数最大字符长度为127
                    //XXF.Log.CommLog.Write("attach参数字符长度："+paramStr.Length);
                    //获取用户OPENID
                    string notify_url = "/WeChat/WxPayNotify".MainSiteFullUrl();//接收微信支付异步通知回调地址，通知url必须为直接可访问的url，不能携带参数
                    ViewBag.wxJsApiParam = PayUtil.PayRequst(Convert.ToInt32((Convert.ToDecimal(orderModel.price) * 100)), 0, openid, tradeCode, description, goodsnamestr, paramStr, notify_url);
                    if (string.IsNullOrEmpty(ViewBag.wxJsApiParam))
                    {
                        return Redirect(ViewBag.CancelUrl);
                    }
                }
                else
                {
                    return RedirectToAction("Index", "GoldShopGoods", new { area = string.Empty, openid = openid });
                }
                return View(orderModel);
            }
            catch (Exception ex)
            {
            }
            return View();
        }

        public ContentResult WxPayNotify()
        {
            ContentResult result = new ContentResult();
            result.ContentType = "text/html";
            try
            {
                //XXF.Log.CommLog.Write("进入订单支付付款回调页面...");
                string message = "";
                ReqResultNotify resultNotify = new ReqResultNotify();
                WxPayData resultData = resultNotify.GetPayResult(Request, out message);

                if (resultData != null)
                {
                    #region 支付成功,返回参数
                    string tradeCode = resultData.GetValue("out_trade_no").ToString();//商户订单号                    
                    string openid = resultData.GetValue("openid") != null ? resultData.GetValue("openid").ToString() : "";

                    string tid = tradeCode.ToString();
                    string zftid = resultData.GetValue("transaction_id").ToString();
                    string fkzh = resultData.GetValue("mch_id").ToString(); //商户号
                    //string attach = resultData.GetValue("attach").ToString();//附加数据
                    //是否关注公众号（Y-关注，N-未关注）
                    string is_subscribe = resultData.GetValue("is_subscribe") != null ? resultData.GetValue("is_subscribe").ToString() : "";
                    #endregion

                    #region 买家支付订单
                    bool isSend = GoldShopOrderBLL.GetPayStatus(BSFConfig.MainConnectString, tid);//是否已推送公众号提醒
                    if (!isSend)
                    {
                        GoldShopOrderModel payModel = new GoldShopOrderModel()
                        {
                            orderid = tid.ToString(),
                            payment_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                            payment_number = fkzh,
                            payment_orderid = zftid,
                            payment_status = "1",
                            payment_type = "2"
                        };

                        bool respay = GoldShopOrderBLL.Update(BSFConfig.MainConnectString, payModel);
                        if (!respay)
                        {
                            //业务数据处理失败
                            result.Content = "failure";
                            return result;
                        }
                        else
                        {
                            decimal paymoney = Convert.ToDecimal(resultData.GetValue("total_fee")) / 100;//支付金额                        
                            //公众号消息推送(只推送已关注公众号的用户)
                            //XXF.Log.CommLog.Write("商品名称字符集合：" + spmcstr);
                            if (is_subscribe == "Y")
                            {
                                if (!string.IsNullOrEmpty(openid))
                                {
                                    //推送成功消息
                                }
                            }
                        }
                    }

                    result.Content = "success";
                    return result;
                    #endregion
                }
                else
                {
                    result.Content = "failure";
                    return result;
                }

            }
            catch (Exception ex)
            {
                result.Content = "failure";
                return result;
            }
        }
    }
}